﻿using Baidu.Api;
using Baidu.Api.Request;
using Baidu.Api.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BaiduTestForm
{
    public partial class Form1 : Form
    {
        private static string CLIENT_ID = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
        private static IBaiduClient client;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://openapi.baidu.com/oauth/2.0/authorize?response_type=token&redirect_uri=oob&scope=netdisk&display=popup&client_id=" + CLIENT_ID);
        }

        #region access_token

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = webBrowser1.Url.ToString();
            if (url.StartsWith("http://openapi.baidu.com/oauth/2.0/login_success"))
            {
                var dic = Baidu.Api.Util.BaiduUtils.SplitUrlQuery(url);
                client = new DefaultBaiduClient(dic["access_token"]);
                webBrowser1.Visible = false;
            }
            else
            {
                webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
                webBrowser1.Visible = true;
            }
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy) return;
            var path = OpenFilePath();
            if (File.Exists(path))
            {
                if (checkBox1.Checked && client.CloudMatch(path))
                {
                    MessageBox.Show("完成!");
                }
                else
                {
                    backgroundWorker1.RunWorkerAsync(path);
                }
            }
        }

        public static string OpenFilePath(string filter = "All Types (*.*)|*.*", string dir = "")
        {
            string path = string.Empty;

            using (var od = new OpenFileDialog())
            {
                od.InitialDirectory = dir;
                od.Filter = filter;
                od.Multiselect = false;
                if (od.ShowDialog() == DialogResult.OK)
                {
                    path = od.FileName;
                }
            }
            return path;
        }

        #region backgroundWorker

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = (string)e.Argument;

            var blockList = new List<string>();

            var req = new SuperFileUploadRequest();

            var array = PCSHelper.GetBytes(path, 512 * 1024).ToArray();

            for (int i = 0; i < array.Length; i++)
            {
                req.File = new FileItem("file.tmp", array[i]);
                var rsp = client.Execute("https://c.pcs.baidu.com/rest/2.0/", req);
                blockList.Add(rsp.MD5);
                int p = (i + 1) * 100 / array.Length;
                backgroundWorker1.ReportProgress(p);
            }

            client.MergeFile(blockList.ToArray(), System.IO.Path.GetFileName(path));
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (progressBar1.InvokeRequired)
            {
                progressBar1.Invoke(new Action(delegate
                {
                    progressBar1.Value = e.ProgressPercentage;
                }));
            }
            else
            {
                progressBar1.Value = e.ProgressPercentage;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("完成!");
            progressBar1.Value = 0;
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            var path = OpenFilePath();

            if (File.Exists(path))
            {
                var sb = new StringBuilder();

                using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    if (fs.Length < BaiduUtils.SLICE_SIZE) return;

                    sb.AppendLine(Path.GetFileName(path));
                    sb.AppendLine(fs.Length.ToString());
                    sb.AppendLine(BaiduUtils.GetMD5(fs));
                    sb.AppendLine(BaiduUtils.GetSliceMD5(fs));
                    sb.AppendLine(BaiduUtils.GetCrc32(fs));

                    fs.Close();
                }

                textBox1.Text = sb.ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var arr = textBox1.Text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            if (arr.Length < 5) return;

            var req = new FileRapidUploadRequest();

            req.ContentLength = ulong.Parse(arr[1]);
            req.ContentMD5 = arr[2];
            req.SliceMD5 = arr[3];
            req.ContentCrc32 = arr[4];

            req.Path = PCSHelper.PathCombine(PCSHelper.APP_Path, arr[0]);
            req.Ondup = "newcopy";
            var rsp = client.Execute(req);

            if (!rsp.IsError) MessageBox.Show("成功!");
        }
    }
}
